package com.hrh.selectsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hrh.selectsystem.common.ErrorCode;
import com.hrh.selectsystem.exception.BusinessException;
import com.hrh.selectsystem.exception.ThrowUtils;
import com.hrh.selectsystem.model.entity.Round;
import com.hrh.selectsystem.model.vo.RoundVO;
import com.hrh.selectsystem.service.RoundService;
import com.hrh.selectsystem.mapper.RoundMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author hetongxue
* @description 针对表【round(轮次)】的数据库操作Service实现
* @createDate 2024-10-26 14:11:52
*/
@Service
public class RoundServiceImpl extends ServiceImpl<RoundMapper, Round>
    implements RoundService{

    @Resource
    private RoundMapper roundMapper;

    /**
     * 分页获取轮次表
     * @param current
     * @param size
     * @return
     */
    @Override
    public Page<RoundVO> listRoundByPage(long current, long size) {
        // 创建分页对象
        Page<Round> page = new Page<>(current, size);

        // 查询分页数据
        Page<Round> roundPage = roundMapper.selectPage(page, null);

        // 将查询结果转换为 RoundVO 列表
        List<RoundVO> roundVOList = roundPage.getRecords().stream()
                .map(this::roundToRoundVO)
                .collect(Collectors.toList());

        // 创建新的分页对象
        Page<RoundVO> roundVOPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        roundVOPage.setRecords(roundVOList);

        return roundVOPage;
    }

    /**
     * 结束当前轮次
     * @return
     */
    @Override
    public boolean endCurrentRound() {
        int startedCount = roundMapper.countStartedRounds();
        // 判断是否有正在运行的轮次
        if (startedCount == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "没有正在运行的轮次，无法结束");
        }
        if (startedCount > 1){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "存在多个正在运行的轮次，无法确定结束哪一个");
        }
        // 结束当前轮次
        boolean result = roundMapper.endCurrentRound();
        // 判断是否成功
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return result;
    }

    /**
     * 启动下一轮次
     * @return
     */
    @Override
    public boolean startNextRound() {
        // 获取第一个未开始的轮次
        Long notStartedRoundId = roundMapper.getFirstNotStartedRoundId();
        // 判断是否存在
        if (notStartedRoundId == null || notStartedRoundId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "没有未开始的轮次，无法启动下一轮次");
        }
        // 判断是否存在已启动的轮次
        if (roundMapper.countStartedRounds() > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "存在已启动的轮次，无法启动下一轮次");
        }
        // 启动下一轮次
        boolean  result = roundMapper.startRound(notStartedRoundId);
        ThrowUtils.throwIf(!result , ErrorCode.OPERATION_ERROR);
        return result;
    }

    /**
     * 重置所有轮次状态
     * @return
     */
    @Override
    public boolean resetAllRounds() {
        // 检查是否有未结束的轮次
        int nonEndedCount = roundMapper.countNonEndedRounds();
        // 如果有未结束的轮次，则不允许重置
        if (nonEndedCount > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "存在未结束的轮次，无法重置");
        }
        // 重置所有轮次
        boolean result = roundMapper.resetAllRounds();
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return result;
    }

    /**
     * 获取当前进行中的轮次
     * @return
     */
    @Override
    public Integer getStartedRound() {
        QueryWrapper<Round> queryWrapper = new QueryWrapper<>();
        String status = "started";
        queryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
        Round round = roundMapper.selectOne(queryWrapper);
        if (round == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "当前无进行中轮次");
        }
        Integer roundNumber = round.getRoundnumber();
        return roundNumber;
    }

    /**
     * 将 Round 对象转换为 RoundVO
     * @param round
     * @return
     */
    private RoundVO roundToRoundVO(Round round) {
        RoundVO roundVO = new RoundVO();
        roundVO.setRoundnumber(round.getRoundnumber());
        roundVO.setStarttime(round.getStarttime());
        roundVO.setEndtime(round.getEndtime());
        roundVO.setStatus(round.getStatus());
        return roundVO;
    }


}




